﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasker.Composition;
using Tasker.Infrastructure.Entities;
using Tasker.Infrastructure.Repositories;
using Tasker.Infrastructure.Repositories.Base;
using Tasker.Repositories.Entities;

namespace Tasker.Repositories
{
    public class UsersRepositoryEF : IUsersRepository
    {
        private EntitiesContext _context = Resolver.Resolve<EntitiesContext>();
        private IContextManager _manager = Resolver.Resolve<IContextManager>();

        public IUser SelectByLogin(string login)
        {
            return _context.Users.SingleOrDefault(user => user.Login == login);
        }

        public IUser SelectById(int id)
        {
            return _context.Users.SingleOrDefault(user => user.Id == id);
        }

        public IEnumerable<IUser> SelectAll()
        {
            return _context.Users.ToList();
        }

        public void Update(IUser entity)
        {
            User res = _context.Users.SingleOrDefault(user => user.Id == entity.Id);
            res.Login = entity.Login;
            res.FirstName = entity.FirstName;
            res.LastName = entity.LastName;
            res.Position = entity.Position;
            res.PasswordHash = entity.PasswordHash;
            res.Comment = entity.Comment;
            res.PictureName = entity.PictureName;
            res.PictureType = entity.PictureType;

            _manager.Save();
        }

        public IUser Create()
        {
            return new User();
        }

        public void Delete(IUser entity)
        {
            User user = _context.Users.SingleOrDefault(ts => ts.Id == entity.Id);
            _context.Users.DeleteObject(user);
        }

        public IUser Insert(IUser entity)
        {
            User res = entity as User;
            _context.Users.AddObject(res);
            _manager.Save();
            return res;
        }
    }
}
